<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{ padding: '5px 12px' }">
      <input type="text" id="idcards_input" v-model="idcard_input" />
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-button @click="getLastDay">前一天</a-button>
              <a-date-picker v-model="today" style="margin: 0 10px" />
              <a-button @click="getNextDay">后一天</a-button>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="学员姓名:">
                <a-input
                  v-model="keywords"
                  placeholder="请输入学员姓名/手机号(回车搜索)"
                  @pressEnter="$refs.table.refresh(true)"
                  style="width: 80%"
                >
                  <a-tooltip slot="suffix" title="请输入学员姓名/手机号">
                    <a-icon type="search" style="color: rgba(0, 0, 0, 0.45)" @click="$refs.table.refresh(true)" />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="padding: 5px 0">
        <a-button style="margin-right: 10px" v-if="isFace" @click="goFace">去考勤</a-button>
        <a-button style="margin-right: 10px" @click="setAttendance">设置</a-button>
        <a-button @click="clickExport">导出</a-button>
      </div>
      <div style="margin: 8px 0" v-if="peoples">
        <a-alert type="warning" style="margin-bottom: 15px; padding: 5px 15px; border: none">
          <span slot="description">
            今日待签到学员<a style="margin: 0 5px" @click="lookToday">{{ peoples.wait_to_sign_in }}</a
            >人，待签退学员<a style="margin: 0 5px" @click="lookTodayOut">{{ peoples.wait_to_sign_out }}</a
            >人
          </span>
        </a-alert>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        style="margin-top: 10px"
        class="user_management_table"
      >
        <span slot="sex" slot-scope="text, record">
          <span v-if="record.student.sex == 1">男</span>
          <span v-else-if="record.student.sex == 2">女</span>
          <span v-else-if="record.student.sex == 0">未知</span>
          <span v-else>-</span>
        </span>
        <span slot="sign_in_time" slot-scope="text, record">
          <span v-if="record.sign_in_time">
            {{ record.sign_in_time | formatDate('h:m') }}
            <span v-if="record.sign_in_type == 1">(刷卡考勤)</span>
            <span v-if="record.sign_in_type == 2">(人脸考勤)</span>
            <span v-if="record.sign_in_type == 3">(老师补签)</span>
          </span>
          <span v-else>-</span>
        </span>
        <span slot="sign_out_time" slot-scope="text, record">
          <span v-if="record.sign_out_time">
            {{ record.sign_out_time | formatDate('h:m') }}
            <span v-if="record.sign_out_type == 1">(刷卡考勤)</span>
            <span v-if="record.sign_out_type == 2">(人脸考勤)</span>
            <span v-if="record.sign_out_type == 3">(老师补签)</span>
          </span>
          <span v-else>-</span>
        </span>
        <span slot="duration" slot-scope="text, record">
          <span v-if="record.duration">{{ record.duration }}</span>
          <span v-else>-</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="delRecord(record.id)"><a-icon type="delete" /></a>
        </span>
      </s-table>

      <!-- 考勤设置弹窗 -->
      <a-modal title="考勤设置" :visible="visible" @cancel="visible = false" :footer="null">
        <a-spin :spinning="loading">
          <div class="flex">
            <div class="left">
              <a-switch v-model="value.quick" @change="setChange" />
            </div>
            <div class="right">
              快捷考勤模式
              <span class="desc">（推荐开启，适用于刷卡考勤）</span>
              <p class="remarks">关闭后，将隐藏右边考勤浮窗。</p>
            </div>
          </div>
          <h4>推送设置</h4>
          <div class="flex">
            <div class="left">
              <a-switch v-model="value.sign_in_notice" @change="setChange" />
            </div>
            <div class="right">学员考勤签到通知</div>
          </div>
          <div class="flex">
            <div class="left">
              <a-switch v-model="value.sign_out_notice" @change="setChange" />
            </div>
            <div class="right">学员考勤签退通知</div>
          </div>
          <h4>关联到课设置</h4>
          <div class="flex">
            <div class="left">
              <a-switch v-model="value.link_class" @change="setChange" />
            </div>
            <div class="right">
              自动关联学员点名到课状态
              <p class="remarks">开启后，根据人脸/刷卡设置考勤记录自动预设学员的点名到课状态，将全部默认未到</p>
            </div>
          </div>
          <h4>自动点名设置</h4>
          <div class="flex">
            <div class="left">
              <a-switch v-model="value.auto_roll_call" @change="setChange" />
            </div>
            <div class="right">
              上课结束，系统自动点名
              <p class="remarks">
                开启后，上课结束后15-30分钟，系统将自动完成点名。
                <br />(未设置上课老师的课次不支持触发自动点名)
              </p>
            </div>
          </div>
        </a-spin>
      </a-modal>
      <a-modal
        title="今日待签到学员"
        :visible="todayInVisible"
        @cancel="todayInVisible = false"
        :footer="null"
        :width="900"
      >
        <a-spin :spinning="spinningStatus">
          <div>凌晨0点后创建的今日排课、审批通过的今日请假不纳入待签到统计范围内</div>
          <a-table
            ref="table"
            size="default"
            rowKey="key"
            :columns="todaycolumns"
            :data-source="loadData1"
            style="margin-top: 10px"
            class="user_management_table"
            :pagination="false"
            :scroll="{ y: 400 }"
          >
            <span slot="face_status" slot-scope="text, record" style="cursor: pointer">
              <span @click="goFace(record)">
                <span v-if="record.faces.length > 0">
                  <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(74, 183, 141)"></span>
                </span>
                <span v-else>
                  <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(191, 191, 191)"></span>
                </span>
              </span>
            </span>
            <span slot="class_name" slot-scope="text, record">
              <div v-if="record.schedules.data.length > 0">
                <div
                  v-for="(item, index) in record.schedules.data"
                  :key="index"
                  :class="{ borderbtm: record.schedules.data.length > 1 }"
                >
                  {{ item.class_start_time }}-{{ item.class_end_time }} {{ item.class_name }}
                </div>
              </div>
              <div v-else>-</div>
            </span>
            <span slot="id_card" slot-scope="text, record">
              <div style="cursor: pointer">
                <span v-if="!record.card_num" @click="addIdCard(record)">
                  <a-icon type="idcard" style="color: rgb(191, 191, 191); font-size: 22px" />
                </span>
                <span v-else><a-icon type="idcard" style="color: rgb(74, 183, 141); font-size: 22px" /></span>
              </div>
            </span>
            <span slot="min_time" slot-scope="text, record">
              <span v-if="record.schedules.min_time">{{ record.schedules.min_time }}</span>
              <span v-else>-</span>
            </span>
            <span slot="NoSignin" slot-scope="text, record">
              <a @click="buqian(record)">签到补卡</a>
            </span>
          </a-table>
          <div style="margin-top: 10px; text-align: right" v-if="pages.pagination">
            <a-pagination v-model="newPage" :total="pages.pagination.total" @change="addPages" />
          </div>
        </a-spin>
      </a-modal>
      <a-modal
        :visible="Visible"
        @cancel="Visible = false"
        :width="400"
        @ok="handleOk"
        :confirm-loading="buqianconfirmLoading"
        :z-index="1001"
      >
        <span slot="title">{{ buqianType == 1 ? '签到' : '签退' }}补卡确认</span>
        <div style="margin: 10px 0 20px">
          将 <a v-if="signInData">{{ signInData.name }}</a> 的签到刷卡时间标记为
        </div>
        <div>
          {{ today1 }}
          <a-time-picker v-model="buqianTime" format="HH:mm" />
        </div>
      </a-modal>
      <!-- 今日待签退学员数 -->
      <a-modal
        title="今日待签退学员"
        :visible="todayOutVisible"
        @cancel="todayOutVisible = false"
        :footer="null"
        :width="900"
      >
        <a-spin :spinning="spinningStatus">
          <a-table
            ref="table"
            size="default"
            rowKey="key"
            :columns="todaycolumns1"
            :data-source="loadData1"
            style="margin-top: 10px"
            class="user_management_table"
            :pagination="false"
            :scroll="{ y: 400 }"
          >
            <span slot="face_status" slot-scope="text, record" style="cursor: pointer">
              <span @click="goFace(record)">
                <span v-if="record.faces.length > 0">
                  <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(74, 183, 141)"></span>
                </span>
                <span v-else>
                  <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(191, 191, 191)"></span>
                </span>
              </span>
            </span>
            <span slot="id_card" slot-scope="text, record">
              <div style="cursor: pointer">
                <span v-if="!record.card_num" @click="addIdCard(record)">
                  <a-icon type="idcard" style="color: rgb(191, 191, 191); font-size: 22px" />
                </span>
                <span v-else><a-icon type="idcard" style="color: rgb(74, 183, 141); font-size: 22px" /></span>
              </div>
            </span>
            <span slot="sign_in_time" slot-scope="text, record">
              <span v-if="record.sign_in_time">{{ record.sign_in_time | times('hh:mm') }}</span>
              <span v-else>-</span>
            </span>
            <span slot="NoSignin" slot-scope="text, record">
              <a @click="buqian1(record)">签退补卡</a>
            </span>
          </a-table>
          <div style="margin-top: 10px; text-align: right" v-if="pages.pagination">
            <a-pagination v-model="newPage1" :total="pages.pagination.total" @change="addPages1" />
          </div>
        </a-spin>
      </a-modal>
      <!-- 添加 绑定卡 -->
    <a-modal
      title="绑定卡片"
      :visible="cardVisible"
      :footer="null"
      @cancel="cardVisible = false"
      width="400px"
      :z-index="1001"
    >
      <div v-if="!idCardData.card_num" style="width: 100%; text-align: center" @click="oncad">
        <img src="~@/assets/img/bigcard.png" alt="" style="width: 50%" />
        <div>请刷卡</div>
      </div>
    </a-modal>
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import moment from 'moment'
import { _debounce } from '@/utils/domUtil'
import {
  attendanceRecord,
  deleteRecord,
  exportRecord,
  attendance,
  submitAttendance,
  statisticsPeople,
  todayList,
  studentList,
  teacherSign,
  addIdCard,
} from '@/api/classconsumes'
export default {
  name: 'byCardList',
  components: {
    STable,
  },
  data() {
    return {
      today: moment(),
      keywords: '',
      queryParam: {
        school_id: this.$store.state.user.school,
      },
      columns: [
        {
          title: '姓名',
          dataIndex: 'student.name',
        },
        {
          title: '性别',
          scopedSlots: { customRender: 'sex' },
        },
        {
          title: '手机号',
          dataIndex: 'student.main_phone',
        },
        {
          title: '签到时间',
          scopedSlots: { customRender: 'sign_in_time' },
        },
        {
          title: '签退时间',
          scopedSlots: { customRender: 'sign_out_time' },
        },
        {
          title: '时长',
          scopedSlots: { customRender: 'duration' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: (parameter) => {
        return attendanceRecord(
          Object.assign(parameter, this.queryParam, {
            name: this.keywords || undefined,
            date: moment(this.today).format('YYYY-MM-DD'),
          })
        ).then((res) => {
          return res
        })
      },
      visible: false,
      loading: false,
      value: {
        quick: false,
        sign_in_notice: false,
        sign_out_notice: false,
        link_class: false,
        auto_roll_call: false,
      },
      isFace: false,
      peoples: undefined,
      spinningStatus: false,
      todayInVisible: false,
      Visible: false,
      buqianconfirmLoading: false,
      loadData1: [],
      todaycolumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          width: 150,
        },
        {
          title: '人脸',
          scopedSlots: { customRender: 'face_status' },
          align: 'center',
        },
        {
          title: '今日排课',
          scopedSlots: { customRender: 'class_name' },
          width: 200,
        },
        {
          title: '待签到时间',
          scopedSlots: { customRender: 'min_time' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'NoSignin' },
        },
      ],
      todaycolumns1: [
        {
          title: '学员姓名',
          dataIndex: 'name',
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          width: 150,
        },
        {
          title: '人脸',
          scopedSlots: { customRender: 'face_status' },
          align: 'center',
        },
        // {
        //   title: '今日排课',
        //   scopedSlots: { customRender: 'sign_in_time' },
        // },
        {
          title: '今日签到时间',
          scopedSlots: { customRender: 'sign_in_time' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'NoSignin' },
        },
      ],
      pages: {},
      newPage: 1,
      buqianType: 1,
      signInData: {},
      buqianTime: null,
      today1: moment().format('YYYY-MM-DD'),
      newPage1: 1,
      todayOutVisible: false,
      cardVisible:false,
      idCardData: {
        card_num: null,
      },
      idcard_input:''
    }
  },
  watch: {
    queryParam: {
      handler(newName, oldName) {
        this.$refs.table.refresh()
        this.classConsumes()
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true,
    },
    idcard_input(newValue, oldValue) {
      document.querySelector('#idcards_input').focus()
      if (newValue != '') {
        this.cardTj1()
      }
    }
  },
  created() {
    console.log(this.$route.path);
    if (this.$route.path == '/appCenter/addFaceExpand/faceList') {
      this.isFace = true
      this.statistics()
      let permission = this.$store.getters.roles.permissionList
      if (permission.indexOf('cardClockIn') != -1) {
        this.todaycolumns.splice(2, 0, {
          title: '考勤卡',
          scopedSlots: { customRender: 'id_card' },
          align: 'center',
        })
        this.todaycolumns1.splice(2, 0, {
          title: '考勤卡',
          scopedSlots: { customRender: 'id_card' },
          align: 'center',
        })
      }
    } else {
      this.isFace = false
    }
  },
  methods: {
    moment,
    //统计签到 签退学员
    statistics() {
      statisticsPeople({ school_id: this.$store.state.user.school })
        .then((res) => {
          this.peoples = res
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败，请刷新后重试')
        })
    },
    lookToday(pageno = 1, pagesize = 10) {
      this.spinningStatus = true
      todayList({ school_id: this.$store.state.user.school, type: 1, pageNo: pageno, pageSize: pagesize })
        .then((res) => {
          this.loadData1 = res.data
          this.pages = res.meta
          this.todayInVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.spinningStatus = false
        })
    },
    addPages(page, pageSize) {
      this.newPage = page
      this.lookToday(page, pageSize)
    },
    goFace(data) {
      let routeData = this.$router.resolve({
        name: 'faceClockIn',
        query: { student_id: data.id, student_name: data.name },
      })
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
      window.open(routeData.href, '_blank')
    },
    buqian(data) {
      this.buqianType = 1
      this.signInData = data
      console.log(this.signInData)
      if (this.signInData.schedules.min_time) {
        this.buqianTime = moment(this.signInData.schedules.min_time, 'HH:mm')
      }
      this.Visible = true
    },
    buqian1(data) {
      this.buqianType = 2
      this.signInData = data
      this.buqianTime = moment(moment().format('HH:mm'), 'HH:mm')
      console.log(this.buqianTime)
      this.Visible = true
    },
    handleOk() {
      this.buqianconfirmLoading = true
      let time = null
      if (this.buqianTime) {
        time = this.today1 + ' ' + moment(this.buqianTime).format('HH:mm')
      } else {
        this.$message.warning('请选择时间!')
        this.buqianconfirmLoading = false
        return
      }
      teacherSign({ student_id: this.signInData.id, type: this.buqianType, time: time })
        .then((res) => {
          if (this.buqianType == 1) {
            this.lookToday()
            this.$message.success('签到补卡成功!')
          } else {
            this.lookTodayOut()
            this.$message.success('签退补卡成功!')
          }

          this.Visible = false
          this.buqianconfirmLoading = false
          this.statistics()
        })
        .catch((err) => {
          if (this.buqianType == 1) {
            this.$message.error(err.data.message || '签到补卡失败')
          } else {
            this.$message.error(err.data.message || '签退补卡失败')
          }
          this.buqianconfirmLoading = false
        })
    },
    lookTodayOut(pageno = 1, pagesize = 10) {
      this.spinningStatus = true
      todayList({ school_id: this.$store.state.user.school, type: 2, pageNo: pageno, pageSize: pagesize })
        .then((res) => {
          this.loadData1 = res.data
          this.pages = res.meta
          this.todayOutVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.spinningStatus = false
        })
    },
    addPages1(page, pageSize) {
      this.newPage1 = page
      this.lookTodayOut(page, pageSize)
    },
    //添加卡片
    oncad() {
      document.querySelector('#idcards_input').focus()
    },
    cardTj1: _debounce(function () {
      this.addSubmit()
    }, 500),
    addIdCard(data) {
      this.idCardData = data
      this.cardVisible = true
      setTimeout(() => {
        document.querySelector('#idcards_input').focus()
      }, 500)
    },
    addSubmit() {
      addIdCard(this.idCardData.id, { card_num: this.idcard_input })
        .then((res) => {
          this.idcard_input = ''
          this.cardVisible = false
          this.lookToday()
          this.$message.success('添加卡号成功')
        })
        .catch((err) => {
          this.idcard_input = ''
          this.$message.error(err.data.message || '刷卡失败，请刷新后重试')
        })
    },
    setAttendance() {
      this.visible = true
      attendance({ school_id: this.$store.state.user.school, key: 'attendance' })
        .then((res) => {
          if (Object.keys(res.value).length !== 0) {
            this.value = res.value
          }
        })
        .catch((err) => {
          this.$message.error(err.data.message || '配置获取失败!')
        })
    },
    setChange() {
      submitAttendance({ school_id: this.$store.state.user.school, key: 'attendance', value: this.value }).then(
        (res) => {
          this.value = res.value
        }
      )
    },
    getLastDay() {
      // .format("YYYY-MM-DD 00:00:00");
      let beginTime = moment(this.today).subtract(1, 'days')
      this.today = beginTime
      this.$refs.table.refresh(true)
    },
    getNextDay() {
      let nextDay = moment(this.today).add(1, 'days')
      this.today = nextDay
      this.$refs.table.refresh(true)
    },
    delRecord(id) {
      let that = this
      this.$confirm({
        title: '删除确认',
        content: (h) => <div>确认删除该条考勤记录？</div>,
        onOk() {
          deleteRecord(id)
            .then((res) => {
              that.$message.success('删除成功')
              that.$refs.table.refresh(true)
            })
            .catch((err) => {
              that.$message.error(err.data.message || '删除失败，请刷新后重试')
            })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },
    clickExport() {
      exportRecord(
        Object.assign({
          school_id: this.$store.state.user.school,
          date: moment(this.today).format('YYYY-MM-DD'),
          name: this.keywords,
        })
      )
        .then((res) => {
          window.location.href = res.url.url + res.url.path
          this.$message.success('导出成功')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '导出失败，请刷新后重试')
        })
    },
    goFace() {
      let routeData = this.$router.resolve({
        name: 'faceClockIn',
        query: { cylType: this.$route.query.cylType },
        params: { id: this.id },
      })
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
      window.open(routeData.href, '_blank')
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@/assets/img/customFormIcon/iconfont.css';
.flex {
  margin-bottom: 10px;
  display: flex;
  .right {
    margin-left: 20px;
    font-size: 16px;
    color: #333;
    .desc {
      font-size: 14px;
      color: #999;
    }
    .remarks {
      font-size: 12px;
      color: #999;
    }
  }
}
h4 {
  margin: 10px 0;
}
.mt20 {
  margin-top: 20px;
}
#idcards_input {
  position: relative;
  top: -100000000px;
}
</style>